<template>
  <div id="custom-table1">
    <el-button @click="insertEvent">新增一条数据并触发校验</el-button>
    <el-button @click="removeCheckboxRow">删除选中</el-button>
    <el-button @click="validAllEvent">整个表格校验</el-button>
    <el-button @click="fullValidEvent">完整表格校验</el-button>
    <el-button @click="submitEvents">提交表格数据</el-button>
    <el-button @click="disableEdit(false)">禁止表格编辑</el-button>
    <el-button @click="disableEdit(true)">开启表格编辑</el-button>

    <!-- TODO:待验证 summary-method="getSummaries" -->
    <div class="right-content1">
      <plx-table-box ref="tableRefs"
        table-size="mini"
        :border="true"
        :show-header="true"
        dragable
        default-search="refWaitTable"
        :table-config="tableConfig"
        :table-max-height="400"
        show-index
        
        show-summary        
        :summary-method="getSummaries"

        :table-sortable="false"
        :show-selection="true"
        :selected-arry.sync="tableSelected"
        @data-change="getDataChange"
        @row-click="rowClickHandel"        
        @selection-change="selectionChangeHandel"
      >
      </plx-table-box>
    </div>
    <plx-table-box ref="tableRefs2"
        table-size="small"
        default-search="userType"
        :table-config="tableConfig2"
        :other-raw="{id:12}" 
        :selected-arry.sync="tableSelected" 
        :auto-scroll="false" 
        :table-height="280"
        :show-selection="true"
        show-index
        dragable
        :show-page="true"
        :click-row-selection="true"
        :border="false"
        @edit-change="editChange" 
        @row-click="rowClickHandel"
        @selection-change="selectionChangeHandel"
        @picklist-click="pickListClick"
        @btnOperate="btnOperate"
      >
          <ux-table-column field="userType" title="用户类型" width="120" :resizable="true"></ux-table-column>
          <ux-table-column field="passwordValidWay" title="密码效验方式" width="120" :resizable="true"></ux-table-column>
          <ux-table-column field="account" title="用户名" width="120" :is-trim="false" :resizable="true"></ux-table-column>
          <ux-table-column field="userName" title="用户姓名" width="120" :resizable="true"></ux-table-column>
          <ux-table-column field="staffCode" title="员工编号" width="120"></ux-table-column>
          <ux-table-column field="gender" title="性别" width="120"></ux-table-column>
          <ux-table-column field="age" title="性别" width="120"></ux-table-column>
          <ux-table-column field="email" title="邮箱" width="120"></ux-table-column>
          <ux-table-column field="phone" title="电话" width="120"></ux-table-column>
          <ux-table-column field="state" title="状态" width="120"></ux-table-column>
          
          <ux-table-column
            field="stockNum"
            title="采购量"
            width="120"
            align="center"
            :edit-render="{'autofocus':'.el-input__inner'}"
          >
            <template v-slot:edit="{row,column}">
              <el-input-number
                v-model="row.stockNum"
                :min="1"
                :max="row.maxNumber || 999"
                size="mini"
                class="edit-cell"
                style="width:100px"
              />
            </template>
          </ux-table-column>
          <ux-table-column 
            title="收货地址"
            :width="300"
            :edit-render="{'autofocus':'.el-input__inner'}"
          >
            <template v-slot:edit="{ row ,column}">
              <input-with-dialog
                  ref="refAddress"
                  v-model="row.position"
                  :props="{label:'address',value:'id'}"
                  :focus-query="true"
                  :remote-url="`https://pandadev.quanyou.com.cn/select-service/api/v1/cusStore/cusStoreAddress?accountCode=1001398`"
                  request-method="get"
                  param-field="searchKey"
                  :dlg-to-body="false"
                  :config="{
                    title:'收货地址',
                    width:'600px',
                    interfacePath:'https://pandadev.quanyou.com.cn/select-service/api/v1/cusStore/cusStoreAddress',
                    method:'get',
                    paramField:'searchKey',
                    filtersRaw:[],
                    paramsRaw:{'accountCode':'1001398'},
                    setting:[
                      {prop:'code',title:'编码',width:80},
                      {prop:'name',title:'名称',width:200},
                      { prop: 'address', title: '收货地址', width:300 }
                    ]
                  }"
                  @click.native.stop=""
                  @click.native.prevent=""
                />
            </template>
            <template v-slot="{ row }">
              {{row.position?row.position[0].address:''}}
            </template>
          </ux-table-column>
    </plx-table-box>

    <el-button  @click="handleSave">获取当前多选行</el-button>
    <el-button  @click="handleToggleAllSelection">切换多选</el-button>
    <div class="right-content">
      <plx-table-box ref="tableRefs1"
        :border="true"
        table-size="mini"
        default-search="userType"
        :table-config="tableConfig"
        :other-raw="{id:12}" 
        :selected-arry.sync="tableSelected" 
        :auto-scroll="false" 
        :off-set="80"
        :show-selection="true"
        show-index
        :dragable="true"
        :show-page="true"
        :click-row-selection="false"
        :showCustomSetting="true"
        @edit-change="editChange" 
        @row-click="rowClickHandel"
        @selection-change="selectionChangeHandel"
        @picklist-click="pickListClick"
        @btnOperate="btnOperate">
        
          <ux-table-column
            field="stockNum"
            title="采购量"
            width="120"
            align="center"
            :edit-render="{'autofocus':'.el-input__inner'}"
          >
            <template v-slot:edit="{row,column}">
              <el-input-number
                v-model="row.stockNum"
                :min="1"
                :max="row.maxNumber || 999"
                size="mini"
                class="edit-cell"
                style="width:100px"
              />
            </template>
          </ux-table-column>
          <ux-table-column 
            title="收货地址"
            field="address"
            :width="300"
            :sort="false"
            :edit-render="{'autofocus':'.el-input__inner'}"
          >
            <template v-slot:edit="{ row ,column}">
              <input-with-dialog
                  ref="refAddress"
                  v-model="row.position"
                  :props="{label:'address',value:'id'}"
                  :focus-query="true"
                  :remote-url="`https://pandadev.quanyou.com.cn/select-service/api/v1/cusStore/cusStoreAddress?accountCode=1001398`"
                  request-method="get"
                  param-field="searchKey"
                  :dlg-to-body="false"
                  :config="{
                    title:'收货地址',
                    width:'600px',
                    interfacePath:'https://pandadev.quanyou.com.cn/select-service/api/v1/cusStore/cusStoreAddress',
                    method:'get',
                    paramField:'searchKey',
                    filtersRaw:[],
                    paramsRaw:{'accountCode':'1001398'},
                    setting:[
                      {prop:'code',title:'编码',width:80},
                      {prop:'name',title:'名称',width:200},
                      { prop: 'address', title: '收货地址', width:300 }
                    ]
                  }"
                  @click.native.stop=""
                  @click.native.prevent=""
                />
            </template>
            <template v-slot="{ row }">
              {{row.position?row.position[0].address:''}}
            </template>
          </ux-table-column>
      </plx-table-box>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'CustomPlTable',
    components: {},
    filters: {},
    props: {},
    data() {
      const nameRules = ({ cellValue, rule }) => {
        if (!cellValue) {
            return new Error('名字必填')
          } else if (cellValue.length < 2) {
            return new Error('名字必须大于2个字符')
        }
      }
      return {
        tableSelected: [],
        tableConfig2:{
          interfacePath: 'https://qup2dev.quanyou.com.cn/ucenter/api/v2/user/page',
          tabIndex:1,
          hideSearchBar:false,// 隐藏搜索，组合查询
          onlySearchBar:false, // 仅显示搜索框
          hideFuncBar:false, // 隐藏整个搜索查询按钮功能区
          onlySettingBtn:false,//是否只显示表格设置
          pageSize: 5,
          tablePage:[5,10,30,50,100],
          btnList:[],          
          checkboxConfig:{
            checkField:'',//复选框：渲染速度更快（建议数据量大时使用，行数据中必须存在该字段，否则无效）
            checkMethod:null,//是否允许勾选的方法，该方法 Function({row}) 的返回值用来决定这一行的 checkbox 是否可以勾选
            checkStrictly:false,//是否严格的遵循父子不互相关联的做法
          },
          editConfig:{
            trigger:'dblclick',
            mode:'cell',
            rules:{
              userName: [
                  { required: true, validator: nameRules}
              ],
              age: [
                  { required: true, message: '年龄必填'}
              ],
              position: [
                  { required: true, message: '收货地址不能为空'}
              ]
            },
            activeMethod:null
          },
        },
        tableConfig: {
          interfacePath: 'https://qup2dev.quanyou.com.cn/ucenter/api/v2/user/page',
          tabIndex: 0,
          hideSearchBar:false,// 隐藏搜索，组合查询
          onlySearchBar:false, // 仅显示搜索框
          hideFuncBar:false, // 隐藏整个搜索查询按钮功能区
          onlySettingBtn:false,//是否只显示表格设置
          pageSize: 5,
          tablePage:[5,10,30,50,100],
          setting: [
            {
              prop: 'userType',
              label: '用户类型',
              minWidth: '120',
              type: 'select',
              propEnum: {
                domainCode: 'platform',
                appCode: 'ucenter',
                dictTypeCode: 'QUP_CUSTOMER_TYPE'
              },
              sort:false,
              sortable:false
            },
            {
              prop: 'coverUrl',
              label: '封面图',
              minWidth: 100,
              overflowHidden: false,
              sortable: false,
              type: 'hidden',
              align: 'center',
              render: (_h, row) => {
                return (<div class='cate_img'><img src='https://filedev.quanyou.com.cn/marketing/group1/M00/00/4D/rB8kPmHfxf2AfYa0AAGGOYiZE4k96.jpeg' style='height:30px' /></div>)
              }
            },
            {
              prop: 'passwordValidWay',
              label: '密码效验方式',
              minWidth: '130',
              type: 'select',
              propEnum: {
                domainCode: 'platform',
                appCode: 'ucenter',
                dictTypeCode: 'PASSWORD_VERIFIERS_TYPE'
              },
              sortable:false
            },
            {
              prop: 'account',
              label: '用户名',
              minWidth: '120',
              className: 'btn-green',
              isButton: true,
              isTrim:false,
              clickFun: ()=>{
                  console.log('点击了')
              },
              sortable:false
            },
            {
              prop: 'userName',
              label: '用户姓名',
              columnKey: 'userName',
              width: '120',
              edit: {
                canEdit: true,
                editType: 'picklist',
                disabled:(row)=>{
                  return row.gender==0
                }
              }
            },
            {
              prop: 'staffCode',
              label: '员工编号',
              // columnKey: 'userId',
              // minWidth: '200',
              width:'300',
              hidden:true
            },
            {
              prop: 'checkVal',
              label: '复选框',
              minWidth: 120,
              edit:{
                editType:'checkbox',
                selectData:[
                  {label:'ckb1',value:0},
                  {label:'ckb2',value:1},
                  {label:'ckb3',value:2},
                ]
              },
              formatData:({checkVal})=>{
                const obj=['ckb1','ckb2','ckb3']
                return checkVal && checkVal.map(v=>{
                  return obj[v]
                }).join(',')
              }
            },
            {
              prop: 'radioVal',
              label: '单选框',
              minWidth: 120,
              edit:{
                editType:'radio',
                selectData:[
                  {label:'radio1',value:0},
                  {label:'radio2',value:1},
                  {label:'radio3',value:2},
                ]
              },
              formatData:({radioVal})=>{
                const obj=['radio1','radio2','radio3']                
                return obj[radioVal]
              }
            },
            {
              prop: 'gender',
              label: '性别',
              type: 'select',
              width: '80',
              propEnum: {
                domainCode: 'platform',
                appCode: 'ucenter',
                dictTypeCode:'QUP_SEX_TYPE'
              },
              formatData: function(data) { return Number(data.gender) === 1 ? '男' : '女' }
            },
            {
              prop: 'age',
              label: '年龄',
              minWidth: 120,
              edit:{
                editType:'number',
                minNumber:10,
                maxNumber:70,
                minFnc:()=>{
                  return 16
                }, // 若minFnc 存在则 minNumber 失效
                maxFnc:()=>{
                  return 20
                }, // 若maxFnc 存在则 maxNumber 失效
              }
            },
            {
              prop: 'email',
              label: '邮箱',
              minWidth: '200',
              required:true,
              edit: {
                canEdit: true,
                editType: 'text',
                filterable: true,
                remote: true,
                remoteUrl: '/ucenter/api/user/ad',
                paramField: 'account',
                defaultProps: {
                  label: 'name',
                  value: 'userId'
                }
              }
            },
            {
              prop: 'phone',
              label: '电话',
              width: '100',
              required:true,
              render: function(_, rows) {
                const {phone} = rows
                return (<span>{phone}</span>)
              },
              edit: {
                canEdit: true,
                editType: 'text',
                maxlength:13
              }
            },
            {
              prop: 'state',
              label: '状态',
              width: '180',
              type: 'select',
              propEnum: {
                domainCode: 'platform',
                appCode: 'ucenter',
                dictTypeCode: 'QUP_USER_STATE'
              },
              edit: {
                canEdit: true,
                editType: 'select',
                /* selectData:[
                    {label:'启用',value:1},
                    {label:'停用',value:0}
                  ], */
                defaultProps: {
                  label: 'compileChildName', // 匹配的下拉字段文字
                  value: 'compileChildId' // 匹配的下拉字段值
                },
                selectData:(row)=>{
                  return [
                    {compileChildName:'启用1',compileChildId:1},
                    {compileChildName:'停用0',compileChildId:0}
                  ]
                } // 若 optionFnc 存在，则使用optionFnc返回值
              }
            },
            {
              prop: 'idNumber',
              label: '身份证号',
              minWidth: 150,
              type:'batch'
            },
            {
              prop: 'source',
              label: '来源',
              minWidth: 150,
              edit: {
                editCondition: (row)=>{
                  console.log(row)
                  return row.userName && row.userName.indexOf('小茜')>-1
                },
                editType: 'select',
                selectData:(row)=>{
                  return [
                    {label:'TOP1',value:'TOP'},
                    {label:'UAC2',value:'UAC'}
                  ]
                }
              },
              formatData:(row)=>{
                return row.source === 'TOP' ? 'TOP1':'UAC2'
              }
            }, 
            {
              prop: 'lastLoginTime',
              label: '最后登录时间',
              minWidth: '160',
              type: 'date',
              edit: {
                canEdit: true,
                editType: 'date',
                disabled:false,
              }
            },
            {
              prop: 'createBy',
              label: '创建人',
              width: '120'
            },
            {
              prop: 'createTime',
              label: '创建时间',
              minWidth: '160',
              type: 'date'
            }
          ],
          btnList:[
            {
              buttonName: '权限按钮1',
              optCode: 'test1',
              outerFlag: true
            },
            {
              buttonName: '权限按钮2',
              optCode: 'test1',
              outerFlag: true
            }
          ],
          
          checkboxConfig:{
            checkField:'',//复选框：渲染速度更快（建议数据量大时使用，行数据中必须存在该字段，否则无效）
            checkMethod:null,//是否允许勾选的方法，该方法 Function({row}) 的返回值用来决定这一行的 checkbox 是否可以勾选
            checkStrictly:false,//是否严格的遵循父子不互相关联的做法
          },
          editConfig:{
            mode:'cell',
            rules:{
              userName: [
                  { required: true, validator: nameRules}
              ],
              /* age: [
                  { required: true, message: '年龄必填'}
              ], */
              email: [
                  { required: true, message: '邮箱必填'}
              ],
              phone: [
                  { required: false, message: '电话必填'}
              ],
              position: [
                  { required: true, message: '收货地址不能为空'}
              ]
            },
            activeMethod:null
          },
        },
        otherFilters:[],
        tableResData:[],
      }
    },
    computed: {},
    watch: {},
    methods:{
      getDataChange(res){
        this.tableResData = res.data.records || []
      },
      // 复选框操作
      selectionChangeHandel(rows) {
        console.log(rows)
        this.tableSelected = rows
      },
      btnOperate(flag) {
        console.log(this.tableSelected)
      },
      // 行内编辑只改变时
      editChange(row, feild) {
        console.log(row[feild],'---')
      },
      // 主表格点击行
      rowClickHandel(data) {
        this.$refs.tableRefs.clearSelection()
        this.$nextTick(() => {
          this.$refs.tableRefs.toggleRowSelection([{row:data.row, selected:true}])
        })
      },
      // 点击行内picklist
      pickListClick(row,columnName) {
        if(columnName === 'userName') {
          this.$alert('改变字段userName', '不同的自定义操作修改字段值', {
            confirmButtonText: '确定',
            callback: action => {
              this.$refs.tableRefs.setEditValue(`字段名${columnName}`)
            }
          })
        }
        if(columnName === 'email') {
          this.$alert('改变字段email', '不同的自定义操作修改字段值', {
            confirmButtonText: '确定',
            callback: action => {
              this.$refs.tableRefs.setEditValue(`字段名${columnName}`)
            }
          })
        }
      },
      removeCheckboxRow(){
        this.$refs.tableRefs.removeCheckboxRow()
      },
      // 校验
      fullValidEvent () {
        // fullValidate完整校验，和 validate 的区别就是会给每一行进行校验
        this.$refs.tableRefs.fullValidate().then(data=> {
          // data就是当前检验不通过的
          if (data) {
            let masStr = ''
            Object.values(data).forEach(errList => {
                console.log(errList)
                errList.forEach(params => {
                    let { rowIndex, column, rules } = params
                    rules.forEach(rule => {
                        masStr += `第 ${rowIndex} 行 ${column.title} 校验错误：${rule.message}; ; ;`
                    })
                })
            })
            // 我用的提示是element-ui的，不要说你没安装element，就说为啥报错
            this.$notify.error({
                title: '错误',
                message: masStr,
                duration: 5000
            });
          } else {
            // 我用的提示是element-ui的，不要说你没安装element，就说为啥报错
            this.$message({
                message: '校验成功',
                type: 'success',
                duration: '1000'
            })
          }
        })
      },
      // 整个表格校验
      validAllEvent () {
        // 1. validate方法 如果你传入一个true， 那么就代表整个表格校验！
        // 2.快速校验，如果存在校验不通过的行，则返回不再继续校验
        this.$refs.tableRefs.validate(true).then(data => {
          if (data) {
              this.$message({
                  message: '校验不通过',
                  type: 'error',
                  duration: '1000'
              })
          } else {
              this.$message({
                  message: '校验成功',
                  type: 'success',
                  duration: '1000'
              })
          }
        })
      },
      // 插入校验
      async insertEvent () {
        const detaultRow =[
          {
          account: "xiaoqian17181",
          alternatePhone: null,
          email: null,
          facePhoto: null,
          gender: 0,
          idNumber: null,
          invalidTime: null,
          isLock: 0,
          lastChangePwdTime: null,
          lastLoginTime: null,
          passwordValidWay: 1,
          phone: "15535242217",
          photo: null,
          pinyin: "xiaoqian17181",
          pinyinShort: "xq17181",
          position: null,
          source: null,
          staffCode: "qy3182906",
          state: 1,
          unlockTime: null,
          userGroup: null,
          userId: "00019dc5-7829-4d98-819d-c578292d98eb111",
          userName: "曾曾测试",
          userType: 2,
          checkVal:[],
          age:null
        },
        {
          account: "xiaoqian17181",
          alternatePhone: null,
          email: null,
          facePhoto: null,
          gender: 0,
          idNumber: null,
          invalidTime: null,
          isLock: 0,
          lastChangePwdTime: null,
          lastLoginTime: null,
          passwordValidWay: 1,
          phone: "15535242217",
          photo: null,
          pinyin: "xiaoqian17181",
          pinyinShort: "xq17181",
          position: null,
          source: null,
          staffCode: "qy3182906",
          state: 1,
          unlockTime: null,
          userGroup: null,
          userId: "00019dc5-7829-4d98-819d-c578292d98eb1112",
          userName: "曾曾测试2",
          userType: 2,
          age:null
        },
        {
          account: "xiaoqian17181",
          alternatePhone: null,
          email: null,
          facePhoto: null,
          gender: 0,
          idNumber: null,
          invalidTime: null,
          isLock: 0,
          lastChangePwdTime: null,
          lastLoginTime: null,
          passwordValidWay: 1,
          phone: "15535242217",
          photo: null,
          pinyin: "xiaoqian17181",
          pinyinShort: "xq17181",
          position: null,
          source: null,
          staffCode: "qy3182906",
          state: 1,
          unlockTime: null,
          userGroup: null,
          userId: "00019dc5-7829-4d98-819d-c578292d98eb1113",
          userName: "曾曾测试3",
          userType: 2,
          age:null
        }
        ]
        //  this.$refs.tableRefs.insertRow()  // 插入空数据
        const {row:newRow,rows:newRows} = await this.$refs.tableRefs.insertRow(detaultRow)// 插入指定数据
        console.log(newRow,newRows)
        // 插入一条数据并触发校验
        // 如果你传入一个row，或者rows rows就是多个row的意思， 那么就代表指定某行校验！
        this.$refs.tableRefs.validate(newRow).then(data => {
          if (data) {
          }
          console.log(data)
        })
        console.log(this.$refs.tableRefs.getTableData())
      },
      // 提交表格数据
      submitEvents () {
        // 获取当前表格的数据（完整的全量表体数据、处理条件之后的全量表体数据、当前渲染中的表体数据、当前渲染中的表尾数据）
        // {fullData, visibleData, tableData, footerData}
        console.log(this.$refs.tableRefs.getTableData())
      },
      disableEdit(falg){
        this.$set(this.tableConfig.editConfig,'canEdit',falg)
        console.log(this.tableConfig.editConfig)
      },
      
      getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总价';
            return;
          }
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] += ' 元';
          } else {
            sums[index] = 'N/A';
          }
        });

        return [sums];
      },
      summaryMethod ({ columns, data }) {
        const means = [] // 合计
        columns.forEach((column, columnIndex) => {
          if (columnIndex === 0) {
            means.push('合计')
          } else {
            const values = data.map(item => Number(item[column.property]));
            // 合计
            if (!values.every(value => isNaN(value))) {
              means[columnIndex] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0);
              means[columnIndex] += ' 元'
            } else {
              means[columnIndex] = '';
            }
          }
        })
        // 返回一个二维数组的表尾合计(不要平均值，你就不要在数组中添加)
        return [means]
      },
      handleSave(){
        console.log(this.tableSelected)
      },
      handleToggleAllSelection(){
        this.$refs.tableRefs1.toggleAllSelection()
      },
    },
    created() {

    }
  }
</script>

<style lang="scss" scoped>
  #custom-table{
    display: flex;
    justify-content: space-between;
    font-size: 12px;

    .right-content{
      min-width: calc(100%);
    }
  }
</style>
